<?php

namespace App\Qingwuit\Services;

use App\Http\Resources\OrderAfterHomeCollection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class CarouselchartsService extends BaseService
{


    // 根据订单ID获取商品数据并格式化
    public function createOrderFormat($params)
    {
        $goods_model = $this->getService('Goods', true);
        $goods_sku_model = $this->getService('GoodsSku', true);

        $userId = $this->getUserId('users');
        $tool = $this->getService('Tool');

        $list = [];
        $this->cartId = []; // 购物车ID 初始化
        foreach ($params['order'] as $v) {
            $data = [];
            $data = $goods_model->with(['store' => function ($q) {
                return $q->select('id', 'store_name', 'store_logo');
            }])->select('id', 'store_id', 'goods_name', 'goods_master_image', 'goods_price', 'goods_stock', 'goods_weight', 'freight_id')->where('id', $v['goods_id'])->first();
            $data['sku_name'] = '-';
            $data['buy_num'] = abs(intval($v['buy_num']));
            $data['sku_id'] = $v['sku_id'];
            if ($v['sku_id'] > 0) {
                $goods_sku = $goods_sku_model->select('id', 'sku_name', 'goods_price', 'goods_stock', 'goods_weight')->where('goods_id', $v['goods_id'])->where('id', $v['sku_id'])->first();
                $data['sku_name'] = $goods_sku['sku_name'];
                $data['goods_price'] = $goods_sku['goods_price'];
                $data['goods_stock'] = $goods_sku['goods_stock'];
                $data['goods_weight'] = $goods_sku['goods_weight'];
            }

            $data['goods_master_image'] =$data['goods_master_image'];
            $data['total'] = round($v['buy_num'] * $data['goods_price'], 2);
            $data['total_weight'] = round($v['buy_num'] * $data['goods_weight'], 2);

            // 判断是否是团购
            $data['collective_id'] = 0;
            if (isset($v['collective_id'])) {
                $data['collective_id'] = $v['collective_id'];
            }

            $list[$data['store']['id']]['goods_list'][] = $data;
            $list[$data['store']['id']]['store_info'] = $data['store'];

            if (empty($list[$data['store']['id']]['store_total_price'])) {
                $list[$data['store']['id']]['store_total_price'] = 0;
            }
            $list[$data['store']['id']]['store_total_price'] = bcadd($list[$data['store']['id']]['store_total_price'], $data['total'], 2);

            // 判断是否库存足够
            if ($v['buy_num'] > $data['goods_stock']) {
                return $this->formatError(__('tip.order.stockErr'));
            }

            // 判断是否是购物车
            if (!empty($params['ifcart'])) {
                $this->cartId[] = $v['cart_id'];
            }
        }

        // 循环查看是否存在优惠券
        $coupon_log_model = $this->getService('CouponLog', true);
        foreach ($list as $k => &$v) {
            $coupon_list = $coupon_log_model->select('id', 'money', 'name')->where('user_id', $userId)->where('store_id', $k)->where('use_money', '<=', $v['store_total_price'])->where('status', 0)->get();
            $v['is_coupon'] = true;
            if ($coupon_list->isEmpty()) {
                $v['is_coupon'] = false;
            }
            $v['coupons'] = $coupon_list;
            if ($v['is_coupon']) {
                $v['coupon_id'] = $coupon_list[0]['id'];
            } else {
                $v['coupon_id'] = 0;
            }
        }

        $list = array_merge($list, []);
        return $this->format($list);
    }

    // base64 代码验证
    public function base64Check()
    {
        $base64 = request()->params ?? '';

        // 如果为空
        if (empty($base64)) {
            return $this->formatError(__('tip.order.error'));
        }

        // 判断是否能解析
        try {
            $params = json_decode(base64_decode($base64), true);
        } catch (\Exception $e) {
            return $this->formatError(__('tip.order.error') . '2');
        }
        return $this->format($params);
    }

    // // 获取订单
    public function getOrders($type = "users")
    {
        $tableModelName = 'Order';
        $order_model = $this->getService($tableModelName, true);
        if ($type == 'users') {
            $userId = $this->getUserId('users');
            $order_model = $order_model->where('user_id', $userId);
        }
        if ($type == 'seller') {
            $store_id = $this->getService('Store')->getStoreId();
            $order_model = $order_model->where('store_id', $store_id);
        }

        $order_model = $order_model->with(['store' => function ($q) {
            return $q->select('id', 'store_name', 'store_logo');
        }, 'user' => function ($q) {
            return $q->select('id', 'username');
        }, 'order_goods']);

        // 订单号
        $order_no  = request()->order_no;
        if (!empty($order_no)) {
            $order_model = $order_model->where('order_no', 'like', '%' . $order_no . '%');
        }

        // 拼团订单ID查询
        $collective_id = request()->collective_id;
        if (!empty($collective_id)) {
            $order_model = $order_model->where('collective_id', $collective_id);
        }

        // 用户ID
        $user_id = request()->user_id;
        if (!empty($user_id)) {
            $order_model = $order_model->where('user_id', $user_id);
        }

        // 店铺ID
        $store_id = request()->store_id;
        if (!empty($store_id)) {
            $order_model = $order_model->where('store_id', $store_id);
        }

        // 下单时间
        $created_at = request()->created_at;
        if (!empty($created_at)) {
            $order_model = $order_model->whereBetween('created_at', [$created_at[0], $created_at[1]]);
        }

        // 订单状态
        if (isset(request()->order_status) && request()->order_status != -1) {
            $order_model = $order_model->where('order_status', request()->order_status);
        }

        // 获取退款订单
        if (isset(request()->is_refund)) {
            $order_model = $order_model->where('order_status', 5)->where('refund_status', 0);
        }

        // 获取退货订单
        if (isset(request()->is_return)) {
            $order_model = $order_model->where('order_status', 5)->where('refund_status', 1);
        }

        $pageData = $order_model->orderBy('id', 'desc')
            ->paginate(request()->per_page ?? 30);
        $data = $pageData;
        if (!empty(request('isResource'))) {
            $tableModelName .=  request('isResource');
        } // 自定义资源文件
        $hasResource = $this->hasResource($pageData, $tableModelName);
        if ($hasResource) {
            $data = $hasResource;
        }
        return $this->format($data);
    }

    // 获取订单信息通过订单ID 默认是需要用用户
    public function getOrderInfoById($id, $auth = 'users')
    {
        $tableModelName = 'Order';
        $order_model = $this->getService($tableModelName, true);

        if ($auth == 'users') {
            $userId = $this->getUserId('users');
            $order_model = $order_model->where('user_id', $userId);
        }

        if ($auth == 'seller') {
            $store_id = $this->getService('Store')->getStoreId();
            $order_model = $order_model->where('store_id', $store_id);
        }

        $pageData = $order_model->with('order_goods')->where('id', $id)->first();
        $data = $pageData;
        if (!empty(request('isResource'))) {
            $tableModelName .=  request('isResource');
        } // 自定义资源文件
        $hasResource = $this->hasResource($pageData, $tableModelName, 1);
        if ($hasResource) {
            $data = $hasResource;
        }
        return $this->format($data);
    }

    // 获取订单状态
    public function getOrderStatusCn($order_info)
    {
        $cn = '未知订单';
        switch ($order_info['order_status']) {
//            case 0:
//                $cn = __('tip.orderCancel');
//                break;
//            case 1:
//                $cn = __('tip.waitPay');
//                break;
//            case 2:
//                $cn = __('tip.waitSend');
//                break;
//            case 3:
//                $cn = __('tip.orderConfirm');
//                break;
//            case 4:
//                $cn = __('tip.waitComment');
//                break;
            case 5:
                if ($order_info['refund']) {
                    if ($order_info['refund_type'] == 0) {
                        $cn = __('tip.orderRefund');
                    } elseif ($order_info['refund_type'] == 1) {
                        $cn = __('tip.orderReturned');
                    } else {
                        $cn = __('tip.orderRefundOver');
                    }
                } else {
                    $cn = __('tip.orderRefund');
                }
                break;
//            case 6:
//                $cn = __('tip.orderCompletion');
//                break;

            case 2:
                $cn = __('tip.waitSend');
                break;
            case 3:
                $cn = __('tip.waitRec');
                break;
            case 6:
                $cn = __('tip.orderCompletion');
                break;


        }
        return $cn;
    }

    // 获取支付类型
    public function getOrderPayMentCn($payment_name)
    {
        $cn = __('tip.waitPay');
        switch ($payment_name) {
            case 'wechat':
                $cn = __('tip.paymentWechat');
                break;
            case 'ali':
                $cn = __('tip.paymentAli');
                break;
            case 'balance':
                $cn = __('tip.paymentMoney');
                break;
        }
        return $cn;
    }
}
